package com.xpchenfrank.service.impl;

import ch.qos.logback.core.net.SyslogOutputStream;
import com.alibaba.fastjson.JSONObject;
import com.xpchenfrank.common.response.RestResponse;
import com.xpchenfrank.service.StockService;
import com.xpchenfrank.utils.CrawlMethodManager;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.DeflateDecompressingEntity;
import org.apache.http.client.entity.GzipDecompressingEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.CharArrayBuffer;
import org.apache.http.util.EntityUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.nio.charset.UnsupportedCharsetException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author xpchen
 * @time 2018/3/8 20:03
 * @Description
 * @copyright Wuxi Yazuo ,Ltd.copyright 2015-2025
 */
@Slf4j
@Component
public class StockServiceImpl implements StockService {

    @Resource
    CrawlMethodManager crawlMethodManager;

    @Override
    public void getPrice() {

       // WebDriver driver = new HtmlUnitDriver();

        // And now use this to visit Google
        //driver.get("http://stockpage.10jqka.com.cn/000333/");
//        driver.get("http://d.10jqka.com.cn/v2/realhead/hs_000333/last.js");
//
//        System.out.println("dirver " + driver.getPageSource());
//
//        String pageSource = driver.getPageSource();
//
//        if(pageSource.contains("hexm_curPrice")) {
//            System.out.println("其实可以找到的");
//        }

        //System.out.println("dirver toString " + driver.toString());

        //WebElement table = driver.findElement(By.cssSelector("#hexm_curPrice"));

        System.setProperty("webdriver.chrome.driver", "D:\\chrome\\chromedriver.exe");
        WebDriver driver = new ChromeDriver();

//		  Map<String, Object> chromeOptions = new HashMap<String, Object>();
//		  chromeOptions.put("user-agent", "Chrome/52.0.2743.98 Mobile Safari/537.36");
//		  DesiredCapabilities capabilities = DesiredCapabilities.chrome();
//		  capabilities.setCapability(ChromeOptions.CAPABILITY, chromeOptions);
//		  WebDriver driver = new ChromeDriver(capabilities);

        System.out.println("driver is complete");
        //System.out.println("driver opt is " + driver.);

        //driver.get("http://store.nike.com/cn/zh_cn/");
        driver.get("http://d.10jqka.com.cn/v2/realhead/hs_000333/last.js");

        String pageSource = driver.getPageSource();
        System.out.println("dirver " + driver.getPageSource());

//        WebElement table = driver.findElement(By.cssSelector("#hexm_curPrice"));

//
//        if(pageSource.contains("hexm_curPrice")) {
//            System.out.println("其实可以找到的");
//        }

        System.out.println("invoke successfully");

    }

    @Override
    public RestResponse getCurrentPrice() {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout(10000).setConnectTimeout(10000)
                .setConnectionRequestTimeout(10000).build();

        JSONObject price = new JSONObject();

//        HttpGet httpGet = new HttpGet("http://nufm.dfcfw.com/EM_Finance2014NumericApplication/JS.aspx?&type=CT&sty=GB20GFBTC&st=z&js=((x))&token=4f1862fc3b5e77c150a2b985b12db0fd&cb=jQuery18308311139936594791_1524208858290&cmd=0003332&_=1524209078361");
//        httpGet.setConfig(requestConfig);
//        CloseableHttpResponse response1 = null;
//        try {
//            response1 = httpclient.execute(httpGet);
//            System.out.println(response1.getStatusLine());
//            HttpEntity httpEntity = response1.getEntity();
//            long contentLength = httpEntity.getContentLength();
//
//            System.out.println("httpEntity is " + httpEntity);
//
//            if (httpEntity.getContentEncoding() != null) {
//                if ("gzip".equalsIgnoreCase(httpEntity
//                        .getContentEncoding().getValue())) {
//                    httpEntity = new GzipDecompressingEntity(httpEntity);
//                } else if ("deflate".equalsIgnoreCase(httpEntity
//                        .getContentEncoding().getValue())) {
//                    httpEntity = new DeflateDecompressingEntity(
//                            httpEntity);
//                }
//            }
//            String result = enCodetoString(httpEntity, "utf-8");// 取出应答字符串

        try {
            String result = crawlMethodManager.crawlPageContentByGet("http://nufm.dfcfw.com/EM_Finance2014NumericApplication/JS.aspx?&type=CT&sty=GB20GFBTC&st=z&js=((x))&token=4f1862fc3b5e77c150a2b985b12db0fd&cb=jQuery18308311139936594791_1524208858290&cmd=0003332&_=1524209078361",
                    "utf-8", false, 0, false, 0, true, 1);

            //尝试从结果中获取价格
            //找到第四个和第五个逗号之间的价格
            String[] results = result.split(",");
            String currPrice = results[6];

            System.out.println("result is " + currPrice);
        } catch (IOException e1) {
            e1.printStackTrace();
        }

        log.info("股票监控的monitor结束");

        return RestResponse.success();
    }

    @Override
    public String get500pxPics() throws IOException {
        System.out.println("AutohomeMonitor is executed");

        CloseableHttpClient httpclient = HttpClients.createDefault();
        RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout(10000).setConnectTimeout(10000)
                .setConnectionRequestTimeout(10000).build();

        JSONObject price = new JSONObject();

        boolean isConditionMet = false;
        HttpGet httpGet = new HttpGet("https://drscdn.500px.org/photo/23645513/m%3D2048/v2?webp=true&sig=07eb90eade78621aea1038d0214506daf6de471d06f07f77481e05b8deccb38f");
        httpGet.setConfig(requestConfig);
        CloseableHttpResponse response1 = null;
        try {
            response1 = httpclient.execute(httpGet);
            try {
                System.out.println(response1.getStatusLine());
                HttpEntity httpEntity = response1.getEntity();
                long contentLength = httpEntity.getContentLength();
                InputStream is = httpEntity.getContent();
                // 根据InputStream 下载文件
                ByteArrayOutputStream output = new ByteArrayOutputStream();
                byte[] buffer = new byte[4096];
                int r = 0;
                long totalRead = 0;
                while ((r = is.read(buffer)) > 0) {
                    output.write(buffer, 0, r);
                    totalRead += r;
                }
                FileOutputStream fos = new FileOutputStream("D:\\temp\\test.jpg");
                output.writeTo(fos);
                output.flush();
                output.close();
                fos.close();
                EntityUtils.consume(httpEntity);

                System.out.println("执行成功");
            } catch (ClientProtocolException e1) {
                e1.printStackTrace();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            response1.close();
            httpclient.close();
        }

        return null;
    }

    public static String enCodetoString(final HttpEntity entity,
                                        final String defaultCharset) throws IOException {
        return enCodetoStringDo(entity,
                defaultCharset != null ? Charset.forName(defaultCharset) : null);
    }

    public static String enCodetoStringDo(final HttpEntity entity,
                                          Charset defaultCharset) throws IOException {
        if (entity == null) {
            throw new IllegalArgumentException("HTTP entity may not be null");
        }
        InputStream instream = entity.getContent();
        if (instream == null) {
            return null;
        }
        try {
            if (entity.getContentLength() > Integer.MAX_VALUE) {
                throw new IllegalArgumentException(
                        "HTTP entity too large to be buffered in memory");
            }
            int i = (int) entity.getContentLength();
            if (i < 0) {
                i = 4096;
            }
            Charset charset = null;
            try {
                // ContentType contentType = ContentType.get(entity);
                // if (contentType != null) {
                // charset = contentType.getCharset();
                // }
            } catch (final UnsupportedCharsetException ex) {
                throw new UnsupportedEncodingException(ex.getMessage());
            }
            if (charset == null) {
                charset = defaultCharset;
            }
            if (charset == null) {
                charset = HTTP.DEF_CONTENT_CHARSET;
            }
            Reader reader = new InputStreamReader(instream, charset);
            CharArrayBuffer buffer = new CharArrayBuffer(i);
            char[] tmp = new char[1024];
            int l;
            while ((l = reader.read(tmp)) != -1) {
                buffer.append(tmp, 0, l);
            }
            return buffer.toString();
        } finally {
            instream.close();
        }
    }
}
